﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Collections.Specialized;

namespace SendCommissioningData
{
    public class HttpWebRequestHelper
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url">接口地址</param>
        /// <param name="postDataStr">数据（文件路径、Json字符串、字符串）</param>
        /// <param name="ContentType">内容类型</param>
        /// <param name="type">调用类型（file=文件,其他)</param>
        /// <param name="hearders">请求头携带信息</param>
        /// <returns></returns>
        public static string HttpPostSync(string url, string postDataStr, string ContentType, string type, Dictionary<string, string> hearders)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = ContentType;// "multipart/form-data";
            request.Method = "GET";
            request.KeepAlive = true;
            request.Credentials = CredentialCache.DefaultCredentials;
            foreach (string key in hearders.Keys)
            {
                request.Headers.Set(key, hearders[key]);
            }
            if (type == "file")
            {//上传文件转为文件流
                FileStream fileStream = new FileStream(postDataStr, FileMode.Open, FileAccess.Read);
                request.ContentLength = fileStream.Length;
                Stream requestStream = request.GetRequestStream();
                byte[] buffer = new byte[4096];
                int bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }
                fileStream.Close();
                requestStream.Close();
            }
            else {
                byte[] postData = Encoding.UTF8.GetBytes(postDataStr);
                request.ContentLength = postData.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(postData, 0, postData.Length);
                requestStream.Close();
            }
            
            WebResponse webResponse = null;
            try
            {
                webResponse = request.GetResponse();
                Stream responseStream = webResponse.GetResponseStream();
                StreamReader streamReader = new StreamReader(responseStream);
                return streamReader.ReadToEnd();
            }
            catch (Exception ex)
            {
                if (webResponse != null)
                {
                    webResponse.Close();
                    webResponse = null;
                }
                return "{code:'101',msg:" + ex.Message+ "}";
            }
        }

        public static string HttpPostSync1(string url, string postDataStr)
        {
            byte[] bs = Encoding.UTF8.GetBytes(postDataStr);
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            req.Method = "post";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = bs.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
            }
            WebResponse wr;
            try
            {
                wr = (HttpWebResponse)req.GetResponse();
            }
            catch (WebException ex)
            {
                wr = (HttpWebResponse)ex.Response;
            }
            Stream sr = wr.GetResponseStream();
            StreamReader reader = new StreamReader(sr, Encoding.UTF8);
            string res = reader.ReadToEnd();
            return res;
        }
    }
}
